package section

import (
	"context"
	// "fmt"
	"strings"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetSectionProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetSectionProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSectionProductListLogic {
	return &GetSectionProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetSectionProductListLogic) GetSectionProductList(in *backend.BaseListReq) (*backend.SectionProductListResp, error) {
	// logrus.Info(fmt.Sprintf("GetSectionProductList BaseListReq: %+v", in))
	// Limit:10 Preload:"sectionProduct:SectionId,ProductId;section:Id,Title,Subtitle" EagerLoad:"sectionProduct:section" PreFilterEntity:"section" PreFilter:"Status,equalTo:1;Type,equalTo:2" VisitorId:10021 PlatformId:1

	if (in.Filter == nil || len(*in.Filter) == 0) && (in.PreFilter == nil || len(*in.PreFilter) == 0) {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	preloadMap, eagerLoadMap := modelx.ParsePreloadAndEagerLoad(in.Preload, in.EagerLoad)
	// logrus.Info(fmt.Sprintf("GetSectionProductList preloadMap: %+v", preloadMap))
	// map[section:[Id Title Subtitle] sectionProduct:[SectionId ProductId]]
	// logrus.Info(fmt.Sprintf("GetSectionProductList eagerLoadMap: %+v", eagerLoadMap))
	// map[sectionProduct:[section]]

	sectionProductEntityName := model.RpcEntityNames.SectionProduct
	if _, ok := model.RpcEntityPreloadMap[sectionProductEntityName]; !ok {
		return &backend.SectionProductListResp{}, nil
	}

	sectionProductRepositoryName := model.RepositoryNames.SectionProduct
	columnMap, ok := model.RepositoryPreloadMap[sectionProductRepositoryName]
	if !ok {
		return &backend.SectionProductListResp{}, nil
	}

	var preFilteredBySection bool
	var sections []*model.Section
	var sids []any
	if in.PreFilterEntity != nil && in.PreFilter != nil {
		sectionEntityName := model.RpcEntityNames.Section
		switch *in.PreFilterEntity {
		case sectionEntityName:
			if _, ok := model.RpcEntityPreloadMap[sectionEntityName]; ok {
				sectionRepositoryName := model.RepositoryNames.Section
				if preColumnMap, ok := model.RepositoryPreloadMap[sectionRepositoryName]; ok {
					filterMap := modelx.ParseFilter(in.PreFilter, preColumnMap)
					// logrus.Info(fmt.Sprintf("GetSectionProductList preFilterMap: %+v", filterMap))
					// map[status:map[equalTo:[1]] type:map[equalTo:[2]]]
					if filterMap == nil {
						return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
					}

					orderBy := modelx.ParseSorter(in.PreSorter, preColumnMap)
					// logrus.Info(fmt.Sprintf("GetSectionProductList preOrderBy: %s", orderBy))

					if len(orderBy) == 0 {
						orderBy = model.SectionColumns.Sort
					}

					res, _, err := l.svcCtx.Section.GetList(l.ctx, model.M{
						"orderBy": orderBy,
					}, -1, filterMap)
					if err != nil {
						return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
					}

					if len(res) == 0 {
						return &backend.SectionProductListResp{}, nil
					}

					preFilteredBySection = true
					for _, v := range res {
						sids = append(sids, v.ID)
						sections = append(sections, v)
					}
				}
			}
		}
	}

	var selectCols []string
	if preloadFields, ok := preloadMap[sectionProductEntityName]; ok {
		selectCols = modelx.ParseSelectColumns(preloadFields, columnMap)
	}

	filterMap := modelx.ParseFilter(in.Filter, columnMap)
	// logrus.Info(fmt.Sprintf("GetSectionProductList filterMap: %+v", filterMap))
	// map[]
	if filterMap == nil {
		if len(sids) == 0 {
			return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
		}

		filterMap = make(map[string]map[string][]any)
	}
	if len(sids) > 0 {
		filterMap[model.SectionProductRelationshipColumns.SectionID] = map[string][]any{
			"in": sids,
		}
	}

	orderBy := modelx.ParseSorter(in.Sorter, columnMap)
	// logrus.Info(fmt.Sprintf("GetSectionProductList orderBy: %s", orderBy))
	//
	if len(orderBy) == 0 {
		orderBy = model.SectionProductRelationshipColumns.Sort
	}

	res, count, err := l.svcCtx.Section.GetRelProductList(l.ctx, model.M{
		"offset":  in.Offset,
		"limit":   in.Limit,
		"orderBy": orderBy,
		"select":  strings.Join(selectCols, ","),
	}, 2, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	hasNextPage, hasPreviousPage := modelx.ParseCount(count)
	resp := &backend.SectionProductListResp{
		HasNextPage:     &hasNextPage,
		HasPreviousPage: &hasPreviousPage,
	}

	var total int64
	if len(res) > 0 {
		var ids []any
		for _, v := range res {
			ids = append(ids, v.SectionID)
		}

		subEntitySettingMap := make(map[string]map[string]*model.ColumnSetting)
		if eagerLoadEntities, ok := eagerLoadMap[sectionProductEntityName]; ok {
			for _, entity := range eagerLoadEntities {
				if entity == "total" {
					_, total, err = l.svcCtx.Section.GetRelProductList(l.ctx, model.M{}, 0, filterMap)
					if err != nil {
						total = 0
					}
					continue
				}

				if entitySettingMap, ok := model.RpcEntityPreloadMap[entity]; ok {
					subEntitySettingMap[entity] = entitySettingMap
				}
			}
		}

		idSectionMap := make(map[uint64]*backend.SectionInfo)
		sectionEntityName := model.RpcEntityNames.Section
		sectionRepositoryName := model.RepositoryNames.Section
		if _, ok := subEntitySettingMap[sectionEntityName]; ok {
			subPreloadFields, hasSubPreloadFields := preloadMap[sectionEntityName]
			subColumnMap, hasSubColumnMap := model.RepositoryPreloadMap[sectionRepositoryName]
			if hasSubPreloadFields && hasSubColumnMap {
				var subSelectCols []string = modelx.ParseSelectColumns(subPreloadFields, subColumnMap)
				subSelectCols = append(subSelectCols, model.AttachmentRelationshipColumns.ObjectID)

				if !preFilteredBySection {
					subFilterMap := make(map[string]map[string][]any)
					subFilterMap[model.SectionColumns.ID] = map[string][]any{
						"in": ids,
					}
					sections, _, err = l.svcCtx.Section.GetList(l.ctx, model.M{
						"orderBy": model.SectionColumns.Sort,
						"select":  strings.Join(subSelectCols, ","),
					}, -1, subFilterMap)
					if err != nil {
						return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
					}
				}

				if len(sections) > 0 {
					for _, v := range sections {
						var sort *uint32
						if v.Sort != uint16(globalkey.SystemDefaultSort) {
							sort = pointy.GetPointer(uint32(v.Sort))
						}

						idSectionMap[v.ID] = &backend.SectionInfo{
							Id:        pointy.GetPointer(v.ID),
							Type:      pointy.GetPointer(uint32(v.Type)),
							Title:     pointy.GetPointer(v.Title),
							Subtitle:  pointy.GetPointer(v.Subtitle),
							PicId:     pointy.GetPointer(v.PicID),
							PicUrl:    pointy.GetPointer(v.PicURL),
							Sort:      sort,
							Status:    pointy.GetPointer(uint32(v.Status)),
							CreatedAt: pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
							UpdatedAt: pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
						}
					}
				}
			}
		}

		for _, v := range res {
			var section *backend.SectionInfo
			if s, ok := idSectionMap[v.SectionID]; ok {
				section = s
			}
			var sort *uint32
			if v.Sort != uint16(globalkey.SystemDefaultSort) {
				sort = pointy.GetPointer(uint32(v.Sort))
			}
			resp.List = append(resp.List, &backend.SectionProductInfo{
				Id:        pointy.GetPointer(v.RelationshipID),
				SectionId: pointy.GetPointer(v.SectionID),
				ProductId: pointy.GetPointer(v.ProductID),
				Sort:      sort,
				Section:   section,
			})
		}
	}
	resp.Total = uint64(total)

	return resp, nil
}
